'use client';

import React, { useState } from 'react';
import { format } from 'date-fns';
import { 
  CalendarIcon, 
  CheckCircleIcon, 
  ClockIcon, 
  PencilIcon, 
  TagIcon, 
  TrashIcon, 
  UserIcon 
} from 'lucide-react';
import { Task } from '@/hooks/use-task';
import { useAuth } from '@/hooks/use-auth';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar } from '@/components/ui/avatar';
import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card';
import { withMemo } from '@/components/hoc/with-memo';
import { ErrorBoundary } from '@/components/ui/error-boundary';
import { normalizeTaskStatus, taskStatusFromApiFormat, taskStatusToApiFormat } from '@/lib/utils';
import { TASK_STATUS, TASK_STATUS_CONFIG } from '@/lib/constants';
import { useRouter } from 'next/navigation';

export interface TaskCardProps {
  task: Task;
  projectId?: string;
  onEdit?: (task: Task) => void;
  onDelete?: (task: Task) => void;
  onStatusChange?: (task: Task, newStatus: string) => void;
  onAssigneeChange?: (task: Task, assigneeId: string) => void;
  className?: string;
  isCompact?: boolean;
  showActions?: boolean;
  showAssignee?: boolean;
  showDueDate?: boolean;
  showTags?: boolean;
}

/**
 * 任务卡片组件
 * 
 * 显示任务信息和操作按钮
 * 
 * @example
 * ```tsx
 * <TaskCard 
 *   task={task} 
 *   onEdit={handleEdit} 
 *   onDelete={handleDelete} 
 * />
 * ```
 */
function TaskCardComponent({
  task,
  onEdit,
  onDelete,
  onStatusChange,
  onAssigneeChange,
  className = '',
  isCompact = false,
  showActions = true,
  showAssignee = true,
  showDueDate = true,
  showTags = true
}: TaskCardProps) {
  const { user } = useAuth();
  const router = useRouter();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  
  // 获取标准化的任务状态
  const normalizedStatus = taskStatusFromApiFormat(task.status);
  
  // 计算任务状态样式
  const getStatusStyles = () => {
    // 使用标准化的状态查找配置
    const statusConfig = TASK_STATUS_CONFIG[normalizedStatus];
    if (statusConfig) {
      return statusConfig.color;
    }
    
    // 回退到原始逻辑
    switch (normalizedStatus) {
      case TASK_STATUS.TODO:
        return 'bg-slate-100 text-slate-700';
      case TASK_STATUS.IN_PROGRESS:
        return 'bg-blue-100 text-blue-700';
      case TASK_STATUS.REVIEW:
        return 'bg-amber-100 text-amber-700';
      case TASK_STATUS.DONE:
        return 'bg-green-100 text-green-700';
      default:
        return 'bg-gray-100 text-gray-700';
    }
  };
  
  // 计算优先级样式
  const getPriorityStyles = () => {
    switch (task.priority) {
      case 'high':
        return 'bg-red-100 text-red-700';
      case 'medium':
        return 'bg-amber-100 text-amber-700';
      case 'low':
        return 'bg-blue-100 text-blue-700';
      default:
        return 'bg-gray-100 text-gray-700';
    }
  };
  
  // 格式化状态文本
  const formatStatus = (status: string) => {
    // 使用标准化的状态查找配置
    const normalizedStatus = taskStatusFromApiFormat(status);
    const statusConfig = TASK_STATUS_CONFIG[normalizedStatus];
    
    if (statusConfig) {
      return statusConfig.label;
    }
    
    // 回退到原始逻辑
    return normalizedStatus.split('-').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };
  
  // 格式化优先级文本
  const formatPriority = (priority: string) => {
    return priority.charAt(0).toUpperCase() + priority.slice(1);
  };
  
  // 处理编辑按钮点击
  const handleEditClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡到卡片
    if (onEdit) {
      onEdit(task);
    } else {
      router.push(`/task/edit/${task.id}`);
    }
  };
  
  // 处理删除按钮点击
  const handleDeleteClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡到卡片
    if (onDelete) {
      onDelete(task);
    }
  };
  
  // 处理状态变更
  const handleStatusChange = (newStatus: string) => {
    if (onStatusChange) {
      // 转换为API格式
      const apiStatus = taskStatusToApiFormat(newStatus);
      onStatusChange(task, apiStatus);
    }
    setIsMenuOpen(false);
  };
  
  // 处理完成按钮点击
  const handleCompleteClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡到卡片
    if (onStatusChange) {
      // 转换为API格式
      const apiStatus = taskStatusToApiFormat(TASK_STATUS.DONE);
      onStatusChange(task, apiStatus);
    }
  };

  // 处理卡片点击，导航到任务详情页面
  const handleCardClick = () => {
    router.push(`/task/${task.id}`);
  };
  
  // 计算是否过期
  const isOverdue = task.dueDate && new Date(task.dueDate) < new Date() && normalizedStatus !== TASK_STATUS.DONE;
  
  return (
    <Card 
      className={`${className} ${isCompact ? 'p-2' : 'p-4'} hover:shadow-md transition-shadow cursor-pointer`}
      onClick={handleCardClick}
    >
      <CardHeader className={`${isCompact ? 'p-2' : 'p-4'} pb-2`}>
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1">
            <h3 className={`font-medium ${isCompact ? 'text-sm' : 'text-base'}`}>
              {task.title}
            </h3>
            <div className="flex flex-wrap gap-1 mt-1">
              <Badge variant="secondary" className={getStatusStyles()}>
                {formatStatus(task.status)}
              </Badge>
              <Badge variant="secondary" className={getPriorityStyles()}>
                {formatPriority(task.priority)}
              </Badge>
            </div>
          </div>
          
          {showActions && (
            <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={handleCompleteClick}
                title="标记为完成"
              >
                <CheckCircleIcon className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={handleEditClick}
                title="编辑任务"
              >
                <PencilIcon className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={handleDeleteClick}
                title="删除任务"
              >
                <TrashIcon className="h-4 w-4" />
              </Button>
            </div>
          )}
        </div>
      </CardHeader>
      
      {!isCompact && task.description && (
        <CardContent className="pt-0 pb-2">
          <p className="text-sm text-muted-foreground line-clamp-2">
            {task.description}
          </p>
        </CardContent>
      )}
      
      <CardFooter className={`flex flex-wrap gap-2 ${isCompact ? 'p-2' : 'p-4'} pt-0`}>
        {showAssignee && (
          <div className="flex items-center gap-1 text-xs text-muted-foreground">
            <UserIcon className="h-3 w-3" />
            {task.assignee ? (
              <div className="flex items-center gap-1">
                <div className="h-4 w-4 rounded-full overflow-hidden bg-muted">
                  {task.assignee.image && <img src={task.assignee.image} alt={task.assignee.name} className="h-full w-full object-cover" />}
                </div>
                <span>{task.assignee.name}</span>
              </div>
            ) : (
              <span>未分配</span>
            )}
          </div>
        )}
        
        {showDueDate && task.dueDate && (
          <div className={`flex items-center gap-1 text-xs ${isOverdue ? 'text-red-500' : 'text-muted-foreground'}`}>
            {isOverdue ? <ClockIcon className="h-3 w-3" /> : <CalendarIcon className="h-3 w-3" />}
            <span>{format(new Date(task.dueDate), 'yyyy-MM-dd')}</span>
          </div>
        )}
        
        {showTags && task.tags && task.tags.length > 0 && (
          <div className="flex items-center gap-1 text-xs text-muted-foreground">
            <TagIcon className="h-3 w-3" />
            <div className="flex flex-wrap gap-1">
              {task.tags.slice(0, 2).map((tag, index) => (
                <Badge key={index} variant="outline" className="text-xs py-0 px-1">
                  {tag}
                </Badge>
              ))}
              {task.tags.length > 2 && (
                <Badge variant="outline" className="text-xs py-0 px-1">
                  +{task.tags.length - 2}
                </Badge>
              )}
            </div>
          </div>
        )}
      </CardFooter>
    </Card>
  );
}

// 使用记忆化HOC优化渲染性能
const MemoizedTaskCard = withMemo(TaskCardComponent);

/**
 * 带错误边界的任务卡片组件
 */
export function TaskCard(props: TaskCardProps) {
  return (
    <ErrorBoundary>
      <MemoizedTaskCard {...props} />
    </ErrorBoundary>
  );
} 